import React, {useEffect, useRef, forwardRef, useImperativeHandle, useState} from 'react'; 
import { Col, message } from 'antd';
import PolicyCommonMent from './policyCommonMent';
import NewComponents from './newComponents';
import moment from 'moment';
import services from '../../../services/api';
import { cloneDeep } from 'lodash';
import '../index.less'
function teps(props,forwardedRef) {
  const [stargyData, setStargyData] = useState({});
  const [submitDatas, setSubmitData] = useState({});
  const childNode = useRef(null);
  const [showLeftBtn, setLeftBtn] = useState(false);
  const [showRightBtn, setRightBtn] = useState(false);
  // useEffect(() => {
  //   const lits = reastData(cloneDeep(props.data));
  //   setStargyData(lits);
  // }, [props.data]);
  useEffect(() => {
    if (props.tabsClick === '1' && Object.keys(props.requestParam).length) {
      stargyHit(); // 类型改了请求数据
    }
  },[props.stepType, props.requestParam, props.grainType, props.timeType, props.tabsClick]);
  useImperativeHandle(forwardedRef, () => ({
    downData
  }));
  // 下载参数
  function downData() {
    let params = getParamsData(submitDatas);
    return params
  };
  // 获取提交参数
  function getParamsData(data) {
    let count = childNode.current.preveIndex;
    let isHideRight = false
    let strategyObj = submitDatas;
    if (typeof data === 'number') {
      count = data
      isHideRight = true
    } else if (data && typeof data !== 'number') {
      strategyObj = data;
      count = 0;
      childNode.current.setPreveFn();
    } else {
      count = 0;
      childNode.current.setPreveFn();
    }
    const times = childNode.current.getCurrentTime(props.timeType, count);
    if (!isHideRight || !count) {
      setRightBtn(false);
    } else if (isHideRight) {
      if (count) {
        setRightBtn(true);
      }
    }
    if (moment(times.current_start) >= moment(times.current_end)) {
      setLeftBtn(true);
    } else {
      setLeftBtn(false);
    }
     if (moment(times.current_start) >= moment(props.requestParam.start)) {
      setLeftBtn(true);
    } else {
      times.current_start = props.requestParam.start;
    };
    const params = {
      ...props.requestParam,
      level: props.stepType,
      strategy_codes: strategyObj.strategy_ids || [],
      type: props.timeType,
      strategy_versions: strategyObj.strategy_versions || [],
      strategy_type: 2,
      ...times
    }
    return params;
  };
  // 请求策略命中
  function stargyHit(data) {
    let params = getParamsData(data);
    services[props.actionType].strategyAnalysis(params).then(res => {
       if (!res.code) {
        const lits = reastData(cloneDeep(res.data));
        setStargyData(lits);
       } else {
         message.error(res.msg);
       }
    });
  };
  // 提交
  function submitData(data) {
    setSubmitData(data);
    stargyHit(data);
  };
  function nextFn(data) {
    stargyHit(data);
    if (!data) {
      setRightBtn(false);
    } else {
      setRightBtn(true);
    }
  }
  // 重置数据
  function reastData(data) {
    if (props.grainType === 'request' || !Object.keys(stargyData).length) return data;
    data.hit_ranking = data.hit_ranking.map(it => {
      it.value = (it.count && ((it.value / it.count) * 10000).toFixed() / 100) || 0;
      return it;
    });
    data.hit_trend = data.hit_trend.map(it => {
      it.value = it.value.map(item => {
          item.requests = (it.count && ((item.requests / it.count) * 10000).toFixed() / 100) || 0;
          return item;
       })
       return it;
    })
    return data;
  };
  const renders = (record, index) => {
    return (
      <>
        <span style={{ marginRight: '10px' }}>{index + 1}</span>
        {record.name}
      </>
    );
  }
  return (
    <>
      <Col key={1} span={24}>
        <PolicyCommonMent
          {...props}
          ref={childNode}
          showLeftBtn={showLeftBtn}
          showRightBtn={showRightBtn}
          nextFn={nextFn}
          lineTitle='策略命中趋势'
          progressTitle='策略命中排名'
          component={<NewComponents {...props} submitData={submitData}></NewComponents>}
          trendList={stargyData.hit_trend || []}
          leftLabel='策略'
          rightLabel={props.grainType === 'request' ? '命中次数' : '命中比率'}
          keyValue={['key', 'value']}
          dataSource={stargyData.hit_ranking || []}
          total={props.grainType === 'request' ? ((stargyData.hit_ranking && stargyData.hit_ranking.length) ? stargyData.hit_ranking[0].count : 100) : 100}
          renderLabel={renders}
          renderValue= {(record, index) => {
            return props.grainType=== 'request' ? record.value : (record.value +'%')
            }
          }
        ></PolicyCommonMent>
      </Col>
    </>
  )
}
export default forwardRef(teps)